package com.xy.service.calculate.lirun.temu;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xy.api.exception.BizException;
import com.xy.api.model.dto.calculate.lirun.temu.TemuLirunProductDTO;
import com.xy.api.model.request.calculate.lirun.temu.TemuLirunProductRequest;
import com.xy.api.model.response.Rows;
import com.xy.api.service.calculate.lirun.temu.ITemuLirunProductService;
import com.xy.auth.UserContext;
import com.xy.mapper.calculate.lirun.temu.TemuLirunProductFormMapper;
import com.xy.mapper.calculate.lirun.temu.TemuLirunProductInstanceMapper;
import com.xy.mapper.calculate.lirun.temu.TemuLirunProductMapper;
import com.xy.mapper.mainData.ProductInstanceMapper;
import com.xy.mapper.mainData.ProductMapper;
import com.xy.model.po.calculate.lirun.temu.TemuLirunProductFormPO;
import com.xy.model.po.calculate.lirun.temu.TemuLirunProductInstancePO;
import com.xy.model.po.calculate.lirun.temu.TemuLirunProductPO;
import com.xy.model.po.mainData.ProductInstancePO;
import com.xy.model.po.mainData.ProductPO;
import com.xy.utils.CustomBeanUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Objects;

@Slf4j
@Service
public class TemuLirunProductServiceImpl implements ITemuLirunProductService {

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private ProductInstanceMapper productInstanceMapper;

    @Autowired
    private TemuLirunProductMapper temuLirunProductMapper;

    @Autowired
    private TemuLirunProductInstanceMapper temuLirunProductInstanceMapper;

    @Autowired
    private TemuLirunProductFormMapper temuLirunProductFormMapper;

    @Override
    public Rows<TemuLirunProductDTO> queryProductList(TemuLirunProductRequest request) {
        Rows<TemuLirunProductDTO> result = new Rows<>();
        LambdaQueryWrapper<TemuLirunProductPO> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.hasText(request.getName())) {
            queryWrapper.like(TemuLirunProductPO::getName, "%" + request.getName() + "%");
        }
        Integer pageNum = request.getPageNum();
        Integer pageSize = request.getPageSize();
        if (null == pageNum) {
            pageNum = 1;
        }
        if (null == pageSize) {
            pageSize = 10;
        }
        Page<TemuLirunProductPO> page = new Page<>(pageNum, pageSize);
        page = temuLirunProductMapper.selectPage(page, queryWrapper);
        result.setTotal(page.getTotal());
        result.setRows(CustomBeanUtil.copyListProperties(page.getRecords(), TemuLirunProductDTO::new));
        return result;
    }

    @Override
    public void editProduct(TemuLirunProductDTO request) {
        request.setPriceUnit("JPY");
        if (null != request.getProductId()) {
            ProductPO existProduct = productMapper.selectById(request.getProductId());
            if (null == existProduct) {
                throw new BizException("产品不存在");
            }
            request.setProductName(existProduct.getName());
            request.setPlOne(existProduct.getPlOne());
            request.setPlTwo(existProduct.getPlTwo());
            request.setVariantCodeOne(existProduct.getVariantCodeOne());
            request.setVariantCodeTwo(existProduct.getVariantCodeTwo());
            request.setProductUnit(existProduct.getProductUnit());
            request.setWeightUnit(existProduct.getWeightUnit());
        }
        if (null != request.getId()) {
            updateProduct(request);
            if (null == request.getProductId()) {
                temuLirunProductMapper.clearProductId(request.getId());
            } else {
                updateTemuLirunProductInstanceByProductId(request.getProductId(), request.getId());
            }
        } else {
            TemuLirunProductPO insertTemuLirunProductPO = addProduct(request);
            if (null != request.getProductId()) {
                addTemuLirunProductFormByProductId(request.getProductId(), insertTemuLirunProductPO.getId());
            }
        }
    }

    private TemuLirunProductPO addProduct(TemuLirunProductDTO product) {
        TemuLirunProductPO record = new TemuLirunProductPO();
        CustomBeanUtil.copyProperties(product, record);
        temuLirunProductMapper.insert(record);
        return record;
    }

    private void updateProduct(TemuLirunProductDTO product) {
        Assert.notNull(product.getId(), "id必填");
        TemuLirunProductPO record = new TemuLirunProductPO();
        CustomBeanUtil.copyProperties(product, record);
        temuLirunProductMapper.updateById(record);
    }

    /**
     * 根据产品更新成本核算实例
     *
     * @param productId
     * @param temuLirunProductId
     */
    private void updateTemuLirunProductInstanceByProductId(Long productId, Long temuLirunProductId) {
        TemuLirunProductPO existTemuLirunProductPO = temuLirunProductMapper.selectById(temuLirunProductId);
        if (Objects.equals(existTemuLirunProductPO.getProductId(), productId)) {
            return;
        }
        deleteTemuLirunProductForm(temuLirunProductId);
        deleteTemuLirunProductInstance(temuLirunProductId);

        addTemuLirunProductFormByProductId(productId, temuLirunProductId);
    }

    /**
     * 根据temuLirunProductId删除TemuLirunProductInstance记录
     *
     * @param temuLirunProductId temu利润核算项目ID
     */
    private void deleteTemuLirunProductInstance(Long temuLirunProductId) {
        LambdaQueryWrapper<TemuLirunProductInstancePO> deleteTemuLirunProductInstanceWrapper = new LambdaQueryWrapper<>();
        deleteTemuLirunProductInstanceWrapper.eq(TemuLirunProductInstancePO::getTemuLirunProductId, temuLirunProductId);
        TemuLirunProductInstancePO deleteTemuLirunProductInstanceRecord = new TemuLirunProductInstancePO();
        deleteTemuLirunProductInstanceRecord.setIsDeleted(1);
        temuLirunProductInstanceMapper.update(deleteTemuLirunProductInstanceRecord, deleteTemuLirunProductInstanceWrapper);
    }

    /**
     * 根据temuLirunProductId删除TemuLirunProductForm记录
     *
     * @param temuLirunProductId temu利润核算项目ID
     */
    private void deleteTemuLirunProductForm(Long temuLirunProductId) {
        LambdaQueryWrapper<TemuLirunProductFormPO> deleteTemuLirunProductFormWrapper = new LambdaQueryWrapper<>();
        deleteTemuLirunProductFormWrapper.eq(TemuLirunProductFormPO::getTemuLirunProductId, temuLirunProductId);
        TemuLirunProductFormPO deleteTemuLirunProductFormRecord = new TemuLirunProductFormPO();
        deleteTemuLirunProductFormRecord.setIsDeleted(1);
        deleteTemuLirunProductFormRecord.setUpdateBy(UserContext.get().getId());
        temuLirunProductFormMapper.update(deleteTemuLirunProductFormRecord, deleteTemuLirunProductFormWrapper);
    }

    /**
     * 更具产品构建核算实例
     *
     * @param productId
     * @param temuLirunProductId
     */
    private void addTemuLirunProductFormByProductId(Long productId, Long temuLirunProductId) {
        Assert.notNull(productId, "产品ID必填");
        LambdaQueryWrapper<ProductInstancePO> productInstanceWrapper = new LambdaQueryWrapper<>();
        productInstanceWrapper
                .eq(ProductInstancePO::getIsDeleted, false)
                .eq(ProductInstancePO::getProductId, productId);
        List<ProductInstancePO> productInstancePOS = productInstanceMapper.selectList(productInstanceWrapper);
        if (!CollectionUtils.isEmpty(productInstancePOS)) {

            for (ProductInstancePO productInstancePO : productInstancePOS) {
                TemuLirunProductFormPO insertTemuLirunProductFormRecord = new TemuLirunProductFormPO();
                insertTemuLirunProductFormRecord.setTemuLirunProductId(temuLirunProductId);
                insertTemuLirunProductFormRecord.setVariantCodeOneValue(productInstancePO.getVariantCodeOneValue());
                insertTemuLirunProductFormRecord.setVariantCodeTwoValue(productInstancePO.getVariantCodeTwoValue());
                insertTemuLirunProductFormRecord.setProductLength(productInstancePO.getProductLength());
                insertTemuLirunProductFormRecord.setProductWidth(productInstancePO.getProductWidth());
                insertTemuLirunProductFormRecord.setProductHeight(productInstancePO.getProductHeight());
                insertTemuLirunProductFormRecord.setPacketLength(productInstancePO.getPacketLength());
                insertTemuLirunProductFormRecord.setPacketWidth(productInstancePO.getPacketWidth());
                insertTemuLirunProductFormRecord.setPacketHeight(productInstancePO.getPacketHeight());
                insertTemuLirunProductFormRecord.setOuterCartonPackCount(productInstancePO.getOuterCartonPackCount());
                insertTemuLirunProductFormRecord.setProductWeight(productInstancePO.getProductWeight());
                insertTemuLirunProductFormRecord.setPackageWeight(productInstancePO.getPackageWeight());

                temuLirunProductFormMapper.insert(insertTemuLirunProductFormRecord);
            }
        }
    }

    @Override
    public void deleteProduct(TemuLirunProductDTO request) {
        Assert.notNull(request.getId(), "TEMU利润核算项目ID必填");
        TemuLirunProductPO deleteRecord = new TemuLirunProductPO();
        deleteRecord.setId(request.getId());
        deleteRecord.setIsDeleted(1);
        deleteRecord.setUpdateBy(UserContext.get().getId());
        temuLirunProductMapper.updateById(deleteRecord);
    }

    @Override
    public TemuLirunProductDTO productDetail(TemuLirunProductDTO request) {
        Assert.notNull(request.getId(), "TEMU利润核算项目ID必填");
        TemuLirunProductDTO temuLirunProduct = new TemuLirunProductDTO();
        TemuLirunProductPO temuLirunProductPO = temuLirunProductMapper.selectById(request.getId());
        CustomBeanUtil.copyProperties(temuLirunProductPO, temuLirunProduct);
        return temuLirunProduct;
    }

    @Override
    public void updateTemuLirunProductStatus(Long temuLirunProductId, Integer status) {
        TemuLirunProductPO updateStatus = new TemuLirunProductPO();
        updateStatus.setId(temuLirunProductId);
        updateStatus.setStatus(status);
        temuLirunProductMapper.updateById(updateStatus);
    }
}
